package com.executor.gateway.filters.global;

import com.executor.gateway.core.ApiConfigManager;
import com.executor.gateway.core.util.CommonUtils;
import com.executor.gateway.model.po.IpList;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Auther: miaoguoxin
 * @Date: 2019/4/28 0028 17:36
 * @Description: ip过滤器
 */
@Component
@Slf4j
public class IpListGlobalFilter implements GlobalFilter, Ordered {
    @Autowired
    private ApiConfigManager apiConfigManager;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String remoteIP = CommonUtils.getRemoteIP(request);
        if (remoteIP == null) {
            response.setStatusCode(HttpStatus.BAD_REQUEST);
            return response.setComplete();
        }
        IpList ipList = apiConfigManager.getIpListMap().get(remoteIP);
        //没有找到Ip名单表示不需要拦截
        if (ipList == null) {
            return chain.filter(exchange);
        }
        if (ipList.getIpListType() == IpList.BLACK_TYPE) {//黑名单
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }



}
